/**
 * HTML代码编辑器组件
 * 专门为HTML代码编辑设计的语法高亮编辑器
 */

import React, { useState, useRef, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { 
  Copy, 
  Download, 
  Maximize2, 
  Minimize2, 
  Code,
  FileText,
  Eye
} from 'lucide-react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism';

/**
 * HTML代码编辑器组件
 * @param {Object} props - 组件属性
 * @param {string} props.value - HTML代码内容
 * @param {function} props.onChange - 内容变化回调
 * @param {string} props.placeholder - 占位符文本
 * @param {boolean} props.readOnly - 是否只读
 * @param {string} props.className - 自定义样式类名
 * @param {boolean} props.showControls - 是否显示控制按钮
 * @param {function} props.onPreview - 预览回调
 * @param {function} props.onValidate - 验证回调
 */
const HtmlEditor = ({
  value = '',
  onChange,
  placeholder = '请输入HTML代码...',
  readOnly = false,
  className = '',
  showControls = true,
  onPreview,
  onValidate
}) => {
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const textareaRef = useRef(null);
  const [cursorPosition, setCursorPosition] = useState(0);

  // 处理内容变化
  const handleChange = (e) => {
    if (onChange) {
      onChange(e.target.value);
    }
  };

  // 处理复制代码
  const handleCopyCode = async () => {
    try {
      await navigator.clipboard.writeText(value);
      alert('代码已复制到剪贴板');
    } catch (error) {
      console.error('复制失败:', error);
      alert('复制失败，请手动复制');
    }
  };

  // 处理下载代码
  const handleDownloadCode = () => {
    const blob = new Blob([value], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'code.html';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // 处理全屏切换
  const handleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  // 处理编辑模式切换
  const handleEditToggle = () => {
    setIsEditing(!isEditing);
    if (!isEditing) {
      // 切换到编辑模式时，聚焦到textarea
      setTimeout(() => {
        if (textareaRef.current) {
          textareaRef.current.focus();
          // 恢复光标位置
          textareaRef.current.setSelectionRange(cursorPosition, cursorPosition);
        }
      }, 100);
    }
  };

  // 处理光标位置变化
  const handleCursorChange = (e) => {
    setCursorPosition(e.target.selectionStart);
  };

  // 获取统计信息
  const getStats = () => {
    const lines = value.split('\n').length;
    const chars = value.length;
    const words = value.split(/\s+/).filter(word => word.trim()).length;
    const size = Math.round(chars / 1024 * 100) / 100;
    
    return { lines, chars, words, size };
  };

  const stats = getStats();

  return (
    <Card className={`${className} ${isFullscreen ? 'fixed inset-4 z-50' : ''}`}>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="flex items-center gap-2">
            <Code className="size-5" />
            HTML代码编辑器
          </CardTitle>
          
          {showControls && (
            <div className="flex items-center gap-2">
              {/* 统计信息 */}
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <Badge variant="outline" size="sm">
                  {stats.lines} 行
                </Badge>
                <Badge variant="outline" size="sm">
                  {stats.chars} 字符
                </Badge>
                <Badge variant="outline" size="sm">
                  {stats.words} 单词
                </Badge>
                <Badge variant="outline" size="sm">
                  {stats.size} KB
                </Badge>
              </div>

              {/* 控制按钮 */}
              <div className="flex items-center gap-1">
                {!readOnly && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleEditToggle}
                    title={isEditing ? "查看模式" : "编辑模式"}
                  >
                    {isEditing ? <FileText className="size-4" /> : <Code className="size-4" />}
                  </Button>
                )}
                
                {onPreview && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={onPreview}
                    title="预览HTML"
                  >
                    <Eye className="size-4" />
                  </Button>
                )}
                
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleCopyCode}
                  disabled={!value}
                  title="复制代码"
                >
                  <Copy className="size-4" />
                </Button>
                
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleDownloadCode}
                  disabled={!value}
                  title="下载代码"
                >
                  <Download className="size-4" />
                </Button>
                
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleFullscreen}
                  title={isFullscreen ? "退出全屏" : "全屏编辑"}
                >
                  {isFullscreen ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}
                </Button>
              </div>
            </div>
          )}
        </div>
      </CardHeader>

      <CardContent>
        <div className="border rounded-lg overflow-hidden">
          {readOnly || !isEditing ? (
            // 只读模式或查看模式 - 显示语法高亮
            <div className="relative">
              <SyntaxHighlighter
                language="html"
                style={tomorrow}
                showLineNumbers={true}
                wrapLines
                wrapLongLines
                className="!m-0 !rounded-none"
                customStyle={{
                  margin: 0,
                  borderRadius: 0,
                  fontSize: '14px',
                  lineHeight: '1.5',
                  minHeight: '400px'
                }}
              >
                {value || placeholder}
              </SyntaxHighlighter>
              
              {/* 编辑模式覆盖层 */}
              {!readOnly && (
                <div 
                  className="absolute inset-0 bg-transparent cursor-text"
                  onClick={handleEditToggle}
                  title="点击进入编辑模式"
                />
              )}
            </div>
          ) : (
            // 编辑模式 - 显示可编辑的textarea
            <div className="relative">
              <textarea
                ref={textareaRef}
                value={value}
                onChange={handleChange}
                onSelect={handleCursorChange}
                onKeyUp={handleCursorChange}
                onMouseUp={handleCursorChange}
                placeholder={placeholder}
                className="w-full h-96 font-mono text-sm border-0 resize-none focus:outline-none"
                style={{
                  background: '#1e1e1e',
                  color: '#d4d4d4',
                  lineHeight: '1.5',
                  fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
                  minHeight: '400px',
                  fontSize: '14px',
                  caretColor: '#ffffff',
                  padding: '16px 16px 16px 60px'
                }}
                spellCheck={false}
                autoComplete="off"
                autoCorrect="off"
                autoCapitalize="off"
              />
              
              {/* 行号显示 */}
              <div 
                className="absolute left-0 top-0 text-sm select-none pointer-events-none"
                style={{
                  background: '#1e1e1e',
                  color: '#858585',
                  fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
                  lineHeight: '1.5',
                  minHeight: '400px',
                  fontSize: '14px',
                  borderRight: '1px solid #333333',
                  padding: '16px 8px 16px 16px',
                  width: '50px',
                  textAlign: 'right'
                }}
              >
                {value.split('\n').map((_, index) => (
                  <div key={index} style={{ height: '21px', lineHeight: '21px' }}>
                    {index + 1}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
};

export default HtmlEditor;
